/*
 *             Copyright (C) 2024 Steve Jrong
 *
 * 	   GitHub Homepage: https://www.github.com/SteveJrong
 *      Gitee Homepage: https://gitee.com/stevejrong1024
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.stevejrong.waiter.mq.message.component;

import com.stevejrong.waiter.common.component.log.LogUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.CompletableFuture;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

/**
 * 工具类 - 领域事件发布器
 * <p>
 * 此类单独提取到通用组件中，是因为在项目中会经常发布领域事件，这里将领域发布器，做为代码级别进行复用，避免在每个需要发布领域事件的应用中都去写一遍领域事件发布器。
 *
 * @author Steve Jrong
 * @since 1.0
 */
@Slf4j
@AllArgsConstructor
public class DomainEventPublisher {

    /**
     * 生产者实例
     */
    private MQProducer producer;

    /**
     * 发送同步消息
     *
     * @param topic      消息主题
     * @param tag        消息标签
     * @param uniqueKey  消息唯一标识
     * @param strMessage 消息体
     */
    @SneakyThrows
    public Mono<SendResult> sendSync(String topic, String tag, String uniqueKey, String strMessage) {
    	Message message = new Message(topic, tag, uniqueKey, strMessage.getBytes(RemotingHelper.DEFAULT_CHARSET));
    	
    	return Mono.fromSupplier(() -> {
    		SendResult sendResult = null;
			try {
				sendResult = producer.send(message);
				
				log.info(LogUtil.builder().append("DomainEventPublisher_sendSync", "同步消息发送完成")
	                    .append("sendStatus", sendResult.getSendStatus())
	                    .append("topic", topic)
	                    .append("tag", tag)
	                    .append("message", message).toString());
			} catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
				log.error(LogUtil.builder().append("DomainEventPublisher_sendSync", "同步消息发送失败")
		                .append("exception", e.getMessage())
		                .append("topic", topic)
		                .append("tag", tag)
		                .append("message", message).toString());
				
				throw new RuntimeException("同步消息发送失败");
			}
			
			return sendResult;
    	});
    }

    /**
     * 发送异步消息
     *
     * @param topic      消息主题
     * @param tag        消息标签
     * @param uniqueKey  消息唯一标识
     * @param strMessage 消息体
     * @return 
     */
    @SneakyThrows
    public Mono<Void> sendAsync(String topic, String tag, String uniqueKey, String strMessage) {
    	Message message = new Message(topic, tag, uniqueKey, strMessage.getBytes(RemotingHelper.DEFAULT_CHARSET));
    	
    	return Mono.fromRunnable(() -> {
    		try {
				producer.send(message, new SendCallback() {
					
					@Override
					public void onSuccess(SendResult sendResult) {
						log.info(LogUtil.builder().append("DomainEventPublisher_sendAsync", "异步消息发送完成")
								.append("topic", topic)
								.append("tag", tag)
								.append("message", message).toString());
					}
					
					@Override
					public void onException(Throwable e) {
						log.error(LogUtil.builder().append("DomainEventPublisher_sendAsync", "异步消息发送失败")
								.append("exception", e.getMessage())
								.append("topic", topic)
								.append("tag", tag)
								.append("message", message).toString());
					}
				});
			} catch (MQClientException | RemotingException | InterruptedException | MQBrokerException e) {
				log.error(LogUtil.builder().append("DomainEventPublisher_sendAsync", "异步消息发送失败")
		                .append("exception", e.getMessage())
		                .append("topic", topic)
		                .append("tag", tag)
		                .append("message", message).toString());
				
				throw new RuntimeException("异步消息发送失败");
			}
    	});
    }

    /**
     * 发送单向消息
     *
     * @param topic      消息主题
     * @param tag        消息标签
     * @param uniqueKey  消息唯一标识
     * @param strMessage 消息体
     */
    @SneakyThrows
    public Mono<Void> sendOneWay(String topic, String tag, String uniqueKey, String strMessage) {
        Message message = new Message(topic, tag, uniqueKey, strMessage.getBytes(RemotingHelper.DEFAULT_CHARSET));
        
        return Mono.fromRunnable(() -> {
        	try {
				producer.sendOneway(message);
				
				log.info(LogUtil.builder().append("DomainEventPublisher_sendOneWay", "单向消息发送完成")
	                    .append("topic", topic)
	                    .append("tag", tag)
	                    .append("message", message).toString());
			} catch (MQClientException | RemotingException | InterruptedException e) {
				log.error(LogUtil.builder().append("DomainEventPublisher_sendOneWay", "单向消息发送失败")
		                .append("exception", e.getMessage())
		                .append("topic", topic)
		                .append("tag", tag)
		                .append("message", message).toString());
				
				throw new RuntimeException("单向消息发送失败");
			}
        });
    }
}